package org.buptsse.ui;

import java.io.File;

import org.buptsse.entity.SellInfoItem;
import org.buptsse.thread.AddSellPhotoThread;
import org.buptsse.thread.DeleteSellPhotoThread;
import org.buptsse.thread.DeleteSellThread;
import org.buptsse.thread.GetSellInfoThread;
import org.buptsse.thread.UpdateSellThread;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ImageService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class ManageBookActivity extends Activity implements OnClickListener, OnLongClickListener{

	private String sellid;
	private String[] conditionNo={"不限","全新","九成新","七八成新","七成新以下"};
	private String longtitude,latitude;
	private String priceStr,bookNumberStr,condition,comment,publisher,author,deleteUri;
	private boolean isLocated=false;
	private SellInfoItem item;
	private TextView bookNameTV,isbnTV,priceTV,bookNumberTV,authorTV,publisherTV,conditionTV,locationTV,commentTV;
	private LinearLayout photosLayout;
	private Button backButton,editButton,saveButton,deleteButton,addButton;
	private EditText bookNameET,priceET,bookNumberET,authorET,publisherET,conditionET,commentET;
	private ProgressDialog pDialog;
	private ImageView deletedImageView;
	private Bitmap addSellPhotoTemp;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				finish();
				break;
			case APPConstant.getSellInfoError:
				Toast.makeText(getApplicationContext(), "获取内容失败", 1000).show();
				finish();
				break;
			case APPConstant.getSellInfoFinish:
				initInfoComponent();
				item=(SellInfoItem) msg.obj;
				fillInfoComponent();
				//Toast.makeText(getApplicationContext(), "更新成功", 1000).show();
				break;
			case APPConstant.updateSellError:
				Toast.makeText(getApplicationContext(), "更新失败", 1000).show();
				break;
			case APPConstant.updateSellFinish:
				//priceStr,bookNumberStr,condition,comment,publisher,author;
				item.setPrice(priceStr);
				item.setBooknumber(bookNumberStr);
				item.setCondition(condition);
				item.setComment(comment);
				item.setPublisher(publisher);
				item.setAuthor(author);
				initInfoComponent();
				fillInfoComponent();
				Toast.makeText(getApplicationContext(), "更新成功", 1000).show();
				break;
			case APPConstant.deleteSellPhotoError:
				Toast.makeText(getApplicationContext(), "删除失败", 1000).show();
				break;
			case APPConstant.deleteSellPhotoFinish:
				Toast.makeText(getApplicationContext(), "删除成功", 1000).show();
				String photos=item.getPhoto();
				photos=photos.replace((String)deletedImageView.getTag(), "");
				item.setPhoto(photos);
				photosLayout.removeView(deletedImageView);
				break;
			case APPConstant.deleteSellError:
				Toast.makeText(getApplicationContext(), "删除失败", 1000).show();
				break;
			case APPConstant.deleteSellFinish:
				Toast.makeText(getApplicationContext(), "删除成功", 1000).show();
				finish();
				break;
			case APPConstant.addSellPhotoError:
				Toast.makeText(getApplicationContext(), "添加照片失败", 1000).show();
				break;
			case APPConstant.addSellPhotoFinish:
				Toast.makeText(getApplicationContext(), "添加照片成功", 1000).show();
				String url=(String) msg.obj;
				item.setPhoto(item.getPhoto()+";"+url);
				ImageView image=new ImageView(getApplicationContext());
				image.setImageBitmap(addSellPhotoTemp);
				image.setOnLongClickListener(ManageBookActivity.this);
				photosLayout.addView(image);
				break;
			}
			if(pDialog!=null)
				pDialog.dismiss();
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 去掉任务条
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		Intent intent=getIntent();
		sellid=intent.getStringExtra("sellid");
		GetSellInfoThread gsit=new GetSellInfoThread(getApplicationContext(), handler, sellid);
		gsit.start();
		ShowWaittingDialog("正在加载内容");
	}
	
	private void initInfoComponent() {
		setContentView(R.layout.l_manage_book_info);
		bookNameTV=(TextView) findViewById(R.id.bookname);
		isbnTV=(TextView) findViewById(R.id.isbn);
		priceTV=(TextView) findViewById(R.id.price);
		bookNumberTV=(TextView) findViewById(R.id.booknumber);
		authorTV=(TextView) findViewById(R.id.author);
		publisherTV=(TextView) findViewById(R.id.publisher);
		conditionTV=(TextView) findViewById(R.id.condition);
		locationTV=(TextView) findViewById(R.id.location);
		commentTV=(TextView) findViewById(R.id.comment);
		photosLayout=(LinearLayout) findViewById(R.id.sell_photos_layout);
		backButton=(Button) findViewById(R.id.rd_back);
		backButton.setOnClickListener(this);
		editButton=(Button) findViewById(R.id.rd_edit);
		editButton.setOnClickListener(this);
		deleteButton=(Button) findViewById(R.id.rd_delete);
		deleteButton.setOnClickListener(this);
	}
	
	private void fillInfoComponent()
	{
		bookNameTV.setText(item.getBookname());
		isbnTV.setText(item.getIsbn());
		priceTV.setText(item.getPrice());
		bookNumberTV.setText(item.getBooknumber());
		authorTV.setText(item.getAuthor());
		publisherTV.setText(item.getPublisher());
		conditionTV.setText(item.getCondition());
		commentTV.setText(item.getComment());
		if(item.getLatitude()!=null && !item.getLatitude().equals("") && item.getLongtitude()!=null && !item.getLongtitude().equals(""))
		{
			locationTV.setText("已定位(点击重新定位)");
			locationTV.setOnClickListener(this);
		}
		String[] photos=item.getPhoto().split(";");
		photosLayout.removeAllViews();
		System.out.println("photos is:"+item.getPhoto());
		for(int i=0;i<photos.length;i++)
		{
			if(photos[i]!=null && !photos[i].equals(""))
			{
				LayoutParams lp=new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
				ImageView image=new ImageView(getApplicationContext());
				image.setImageBitmap(ImageService.getImageByUrl(photos[i]));
				photosLayout.addView(image, lp);
			}
		}
	}
	
	private void initEditComponent()
	{
		setContentView(R.layout.l_manage_book_edit);
		bookNameET=(EditText) findViewById(R.id.bookname);
		priceET=(EditText) findViewById(R.id.price);
		bookNumberET=(EditText) findViewById(R.id.booknumber);
		authorET=(EditText) findViewById(R.id.author);
		publisherET=(EditText) findViewById(R.id.publisher);
		conditionET=(EditText) findViewById(R.id.condition);
		conditionET.setOnClickListener(this);
		commentET=(EditText) findViewById(R.id.comment);
		backButton=(Button) findViewById(R.id.rd_back_edit);
		backButton.setOnClickListener(this);
		saveButton=(Button) findViewById(R.id.rd_save);
		saveButton.setOnClickListener(this);
		addButton=(Button) findViewById(R.id.rd_add_photo);
		addButton.setOnClickListener(this);
		photosLayout=(LinearLayout) findViewById(R.id.sell_photos_layout);
	}

	private void fillEditComponent()
	{
		bookNameET.setText(item.getBookname());
		priceET.setText(item.getPrice());
		bookNumberET.setText(item.getBooknumber());
		authorET.setText(item.getAuthor());
		publisherET.setText(item.getPublisher());
		conditionET.setText(item.getCondition());
		commentET.setText(item.getComment());
		String[] photos=item.getPhoto().split(";");
		System.out.println("photos is:"+item.getPhoto());
		photosLayout.removeAllViews();
		for(int i=0;i<photos.length;i++)
		{
			if(photos[i]!=null && !photos[i].equals(""))
			{
				LayoutParams lp=new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
				ImageView image=new ImageView(getApplicationContext());
				image.setImageBitmap(ImageService.getImageByUrl(photos[i]));
				image.setTag(photos[i]);
				image.setOnLongClickListener(this);
				photosLayout.addView(image,lp);
			}
		}
	}
	
	private void updateSell()
	{
		priceStr=priceET.getText().toString();
		try{
			Integer.parseInt(priceStr);
		}catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(), "输入的价格错误", 1000).show();
			return;
		}
		bookNumberStr=bookNumberET.getText().toString();
		try{
			Integer.parseInt(bookNumberStr);
		}catch (NumberFormatException e) {
			Toast.makeText(getApplicationContext(), "输入的数量错误", 1000).show();
			return;
		}
		condition=conditionET.getText().toString();
		comment=commentET.getText().toString();
		publisher=publisherET.getText().toString();
		author=authorET.getText().toString();
		UpdateSellThread ust=new UpdateSellThread(getApplicationContext(), handler, sellid, condition, priceStr, bookNumberStr, comment, publisher, author, publisher, author);
		if(isLocated==true)
		{
			ust.setLatitude(latitude);
			ust.setLongtitude(longtitude);
		}
		ust.start();
		ShowWaittingDialog("正在获取商品信息");
	}
	
	public void ShowWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}	
	
	private void conditionDialog() {
		new AlertDialog.Builder(this).setTitle("新旧程度")
				.setItems(conditionNo, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						conditionET.setText(conditionNo[which]);
					}
				}).show();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.rd_back:
			finish();
			break;
		case R.id.rd_back_edit:
			AlertDialog.Builder builder = new Builder(ManageBookActivity.this);
			builder.setMessage("确认返回吗？");
			builder.setTitle("提示");
			builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					initInfoComponent();
					fillInfoComponent();
				}
			});
			builder.setNegativeButton("取消", null);
			builder.create().show();
			break;
		case R.id.rd_save:
			updateSell();
			break;
		case R.id.rd_edit:
			initEditComponent();
			fillEditComponent();
			break;
		case R.id.rd_delete:
			AlertDialog.Builder builder2 = new Builder(ManageBookActivity.this);
			builder2.setMessage("确认删除吗？");
			builder2.setTitle("提示");
			builder2.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//删除sell
					DeleteSellThread dst=new DeleteSellThread(getApplicationContext(), handler, sellid);
					dst.start();
					ShowWaittingDialog("正在删除");
				}
			});
			builder2.setNegativeButton("取消", null);
			builder2.create().show();
			break;
		case R.id.rd_add_photo:
			//添加实物照片
			ChooseImage();
			break;
		case R.id.location:
			break;
		case R.id.condition:
			conditionDialog();
			break;
		}
	}

	@Override
	public boolean onLongClick(final View arg0) {
		AlertDialog.Builder builder = new Builder(ManageBookActivity.this);
		builder.setMessage("确认删除吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				deletedImageView=(ImageView) arg0;
				DeleteSellPhotoThread dspt=new DeleteSellPhotoThread(getApplicationContext(), handler, sellid, (String)deletedImageView.getTag());
				dspt.start();
				ShowWaittingDialog("正在执行操作");
			}
		});
		builder.setNegativeButton("取消", null);
		builder.create().show();
		return false;
	}
	
	String[] type={"拍照","从文件中选择"};
	final int TAKE_PHOTO_WITH_DATA=1;
	final int TAKE_PHOTO_FROM_FILE=2; 
	final int PHOTO_CROP_FINISH=3;
	final int GET_ISBN=4;
	private void ChooseImage()
	{
		new AlertDialog.Builder(this).setTitle("选择照片")
		.setItems(type, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					//拍照
					//Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					Intent intent = new Intent(  
                            MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri  
                            .fromFile(new File(Environment  
                                    .getExternalStorageDirectory(),  
                                    "cloudLearning_temp.jpg")));
					startActivityForResult(intent, TAKE_PHOTO_WITH_DATA);
					break;

				case 1:
					//从文件选择
					Intent intent2 = new Intent(Intent.ACTION_PICK, null);  
	                /* 开启Pictures画面Type设定为image */    
					intent2.setDataAndType(  
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
                            "image/*");  
	                startActivityForResult(intent2, TAKE_PHOTO_FROM_FILE);
					break;
				}
			}
		}).create().show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		if(resultCode!=RESULT_OK)
            return;
		switch (requestCode) {
		case TAKE_PHOTO_WITH_DATA:
			File temp = new File(Environment.getExternalStorageDirectory()  
                    + "/cloudLearning_temp.jpg");  
            startPhotoZoom(Uri.fromFile(temp));
			break;

		case TAKE_PHOTO_FROM_FILE:
			startPhotoZoom(data.getData());
			break;
		case PHOTO_CROP_FINISH:
			Bitmap photoCroped = (Bitmap) data.getExtras().get("data");
			if(photoCroped!=null){
				addSellPhotoTemp=photoCroped;
				AddSellPhotoThread addSellPhotoThread=new AddSellPhotoThread(getApplicationContext(), handler, sellid, photoCroped);
				addSellPhotoThread.start();
				ShowWaittingDialog("正在上传照片");
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	public void startPhotoZoom(Uri uri) {  
        /*  
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页  
         * yourself_sdk_path/docs/reference/android/content/Intent.html  
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,  
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么  
         * 制做的了...吼吼  
         */ 
        Intent intent = new Intent("com.android.camera.action.CROP");  
        intent.setDataAndType(uri, "image/*");  
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪  
        intent.putExtra("crop", "true");  
        // aspectX aspectY 是宽高的比例  
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
        // outputX outputY 是裁剪图片宽高  
        intent.putExtra("outputX", 150);  
        intent.putExtra("outputY", 150);  
        intent.putExtra("return-data", true);  
        startActivityForResult(intent, PHOTO_CROP_FINISH);  
    }  
}